package edu.sctu.jsoup.service;

import edu.sctu.jsoup.entity.ArticleEntity;
import edu.sctu.jsoup.repo.ArticleRepo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ArticleService {

    @Autowired
    private ArticleRepo articleRepo;

    public void run(){


        try {
            Document document = Jsoup.connect("http://www.sctu.edu.cn").get();

            System.out.println(document.body());

            Elements elements = document.select("div.tab").first().select("li");

            for (Element element : elements){

                String pubDate = element.select("dl").first().text();

                String title = element.select("a").first().text();

                String url = element.select("a").attr("herf");

                System.out.println(pubDate+"|"+title+url);

                ArticleEntity entity = new ArticleEntity();
                entity.setTitle(title);
                entity.setUrl(url);
                entity.setPubDate(pubDate);

                articleRepo.save(entity);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
